package com.mayikt.main.api.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mayikt.common.core.api.BaseApiService;
import com.mayikt.common.core.api.BaseResponse;
import com.mayikt.common.core.utils.MD5Utils;
import com.mayikt.main.api.RegisterService;
import com.mayikt.main.api.impl.entity.SysUser;
import com.mayikt.main.api.impl.entity.SysUserId;
import com.mayikt.main.api.impl.mapper.SysUserIdMapper;
import com.mayikt.main.api.impl.mapper.SysUserMapper;
import com.mayikt.main.api.impl.utils.SaltUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class RegisterServiceImpl extends BaseApiService<String> implements RegisterService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserIdMapper sysUserIdMapper;

    @Override

    public BaseResponse<String> register(String phoneNumber, String password) {
        //验证参数是否为空
        if (Strings.isBlank(phoneNumber)) {
            return setResultError("phoneNumber is null");

        }
        if (Strings.isBlank(password)) {
            return setResultError("password is null");

        }
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("phone_number", phoneNumber);
        //根据手机号查询相同的号码
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        if (sysUser != null) {
            return setResultError("该手机号码已存在");
        }
        // 对密码加密
        String salt = SaltUtils.getSalt();
        String md5Password = MD5Utils.md5(password + salt);
        sysUser = new SysUser(phoneNumber, md5Password, salt);
        // 利用临时表获取用户全部userid
        SysUserId sysUserId = new SysUserId();
        int insert = sysUserIdMapper.getUserId(sysUserId);
        if (insert <= 0) {
            return setResultError();
        }
        sysUser.setId(sysUserId.getUserId());
        int result = sysUserMapper.insert(sysUser);
        return setResultDb(result);
    }
}
